<template>
  <div class="w-100 h-100 p-4 border-box bg-deep color-white flex-vertical font3 ">
    <!--养殖场选择-->
  


    <div class="flex-content h-50 flex-item">
      <div class="flex-content flex-vertical bg-cover mr-4 py-3 px-4 round-md border-box" v-loading="loading1"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <div class="flex-label flex-item justify-content-between align-items-center">
          <div class="flex-label">温度</div>
          <div class="flex-content d-flex justify-content-end pl-4">
            <el-date-picker v-model="date1" type="daterange" range-separator="-" start-placeholder="开始日期"
              end-placeholder="结束日期" format='yyyy-MM-dd' value-format='yyyy-MM-dd' />
            <el-button icon="el-icon-search" type="primary" v-loading="loading1"
              @click="update_charts(date1, 'TEM', checkOptions1); loading1 = true">查询</el-button>
          </div>

        </div>
        <div class="flex-content flex-item pt-3">
          <div style="width: 30%;" class="w-30">
            <el-checkbox-group v-model="checkVal1" :max="max">>
              <el-checkbox v-for="name in checkOptions" :key="name.id" :label="name.id" :value="name.id">
                {{ name.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="flex-content d-flex justify-content-center chart1 overflow-hidden no-scroll"></div>
        </div>
      </div>
      <div class="flex-content flex-vertical bg-cover mr-4 py-3 px-4 round-md border-box" v-loading="loading2"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <div class="flex-label flex-item justify-content-between align-items-center">
          <div class="flex-label">PH</div>
          <div class="flex-content d-flex justify-content-end pl-4">
            <el-date-picker v-model="date2" type="daterange" range-separator="-" start-placeholder="开始日期"
              end-placeholder="结束日期" format='yyyy-MM-dd' value-format='yyyy-MM-dd' />
            <el-button icon="el-icon-search" type="primary" v-loading="loading2"
              @click="update_charts(date2, 'PH', checkOptions2); loading2 = true">查询</el-button>
          </div>

        </div>
        <div class="flex-content flex-item pt-3">
          <div style="width: 30%;" class="w-30">
            <el-checkbox-group v-model="checkVal2" :max="max">>
              <el-checkbox v-for="name in checkOptions" :key="name.id" :label="name.id" :value="name.id">
                {{ name.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <div class="flex-content d-flex justify-content-center chart2 overflow-hidden no-scroll"></div>
        </div>
      </div>
    </div>
    <div class="flex-content h-50 flex-item">


      <div class="flex-content flex-vertical bg-cover mr-4 py-3 px-4 round-md border-box" v-loading="loading3"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <div class="flex-label flex-item justify-content-between align-items-center">
          <div class="flex-label">溶氧</div>
          <div class="flex-content d-flex justify-content-end pl-4">
            <el-date-picker v-model="date3" type="daterange" range-separator="-" start-placeholder="开始日期"
              end-placeholder="结束日期" format='yyyy-MM-dd' value-format='yyyy-MM-dd' />
            <el-button icon="el-icon-search" type="primary" v-loading="loading3"
              @click="update_charts(date3, 'O2', checkOptions3); loading3 = true">查询</el-button>
          </div>
        </div>
        <div class="flex-content flex-item pt-3">
          <div style="width: 30%;" class="w-30">
            <el-checkbox-group v-model="checkVal3" :max="max">>
              <el-checkbox v-for="name in checkOptions" :key="name.id" :label="name.id" :value="name.id">
                {{ name.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <div class="flex-content d-flex justify-content-center chart3 overflow-hidden no-scroll"></div>
        </div>
      </div>
      <div class="flex-content flex-vertical bg-cover mr-4 py-3 px-4 round-md border-box" v-loading="loading4"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <div class="flex-label flex-item justify-content-between align-items-center">
          <div class="flex-label">电导</div>
          <div class="flex-content d-flex justify-content-end pl-4">
            <el-date-picker v-model="date4" type="daterange" range-separator="-" start-placeholder="开始日期"
              end-placeholder="结束日期" format='yyyy-MM-dd' value-format='yyyy-MM-dd' />
            <el-button icon="el-icon-search" type="primary" v-loading="loading4"
              @click="update_charts(date4, 'CONDUCTANCE', checkOptions4); loading4 = true">查询</el-button>
          </div>
        </div>
        <div class="flex-content flex-item pt-3">
          <div style="width: 30%;" class="w-30">
            <el-checkbox-group v-model="checkVal4" :max="max">>
              <el-checkbox v-for="name in checkOptions" :key="name.id" :label="name.id" :value="name.id">
                {{ name.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <div class="flex-content d-flex justify-content-center chart4 overflow-hidden no-scroll"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

const colorList = ['#28D9E2', '#FE9601', '#FD5C66', '#8c8afd', '#f08afd', '#fbfd8a', '#8afd90'];
import { homelist, get_equipments, getHistoryData } from '@/request/api';
import * as echarts from 'echarts'

export default {
  name: 'dataHistory',
  data() {
    return {
      loading1: false,
      loading2: false,
      loading3: false,
      loading4: false,
      max: 5,
      chartObj: {},
      checkOptions: [],//设备列表
      breed_bases: [],//基地列表,
      date1: '',
      showdata1: [],
      checkVal1: [],
      checkOptions1: [],//选择的设备列表
      selected_base:'',
      // chart1: echarts.init(document.getElementsByClassName('chart1')[0]),
      chart1: '',
      date2: '',
      showdata2: [],
      checkVal2: [],
      checkOptions2: [],//选择的设备列表
      // chart2: echarts.init(document.getElementsByClassName('chart2')[0]),
      chart2: '',
      date3: '',
      showdata3: [],
      checkVal3: [],
      checkOptions3: [],//选择的设备列表
      // chart3: echarts.init(document.getElementsByClassName('chart3')[0]),
      chart3: '',
      date4: '',
      showdata4: [],
      checkVal4: [],
      checkOptions4: [],//选择的设备列表
      chart4: '',
      chart_dates1: {},// 绘图数据
      chart_dates2: {},// 绘图数据
      chart_dates3: {},// 绘图数据
      chart_dates4: {},// 绘图数据
      pieData: [],
    }
  },
  // created() {

  // },
  mounted() {
    this.getList();

    // console.log(this.breed_bases)

  },
  computed: {
    isCollapse() {
      return this.$parent.isCollapse
    }
  },
  watch: {
    // 菜单折叠导致窗口变化后重新渲染大小
    isCollapse(val) {
      setTimeout(this.resize, val ? 0 : 200)
    },
    selected_base: {//根据选择的基地渲染不同的数据

      handler: function (newV) {
        //一般有两个参数值，newV和oldValues，分别获取更新后的新值和更新后的旧值
        //执行getDataTotal方法
        this.updateBaseDataByName(newV);
        this.renderLine('chart1', this.chart_dates1);
        this.renderLine('chart2', this.chart_dates2);
        this.renderLine('chart3', this.chart_dates3);
        this.renderLine('chart4', this.chart_dates4);
      },
      immediate: true//立即执行
    },
    checkVal1: {
      handler: function (val) {
        // console.log(val)
        // var showdata = [];
        this.checkOptions1 = this.getOption(val)
        this.showdata1 = this.getshowdata(this.chart_dates1, val)


        // this.renderLine('chart1', { x: this.chart_dates1.x, y: showdata });

      },
      immediate: true,
    },
    checkVal2: {
      handler: function (val) {
        // var showdata = [];
        this.checkOptions2 = this.getOption(val)
        this.showdata2 = this.getshowdata(this.chart_dates2, val)
      },
      immediate: true,
    },
    checkVal3: {
      handler: function (val) {
        // var showdata = [];
        this.checkOptions3 = this.getOption(val)
        this.showdata3 = this.getshowdata(this.chart_dates3, val)
      },
      immediate: true,
    },
    checkVal4: {
      handler: function (val) {
        // var showdata = [];
        this.checkOptions4 = this.getOption(val)
        this.showdata4 = this.getshowdata(this.chart_dates4, val)
      },
      immediate: true,
    },
    showdata1: {
      handler: function (val) {
        this.renderLine('chart1', val);
      }


    },
    showdata2: {
      handler: function (val) {
        this.renderLine('chart2', val);
      }

    },
    showdata3: {
      handler: function (val) {
        this.renderLine('chart3', val);
      }

    },
    showdata4: {
      handler: function (val) {
        this.renderLine('chart4', val);
      }

    },


  },

  methods: {
    getOption(val) {
      var Option = [];
      val.forEach(i => {
        Option.push(this.checkOptions.find(j =>{ return j.id==i}))
      })
      // console.log(Option)
      return Option;
    },
    getshowdata(data, showin) {//根据选择的id 展示对应的数据
      var showdata = [];
      showin.forEach(i => {
        showdata.push({
          dimensions: data.y.find(j=>{ return j.id==i}).dimensions,//[{type: 'time',name:''},{type:'value',name:data.y[i].dimensions[1]}],
          source:data.y.find(j=>{ return j.id==i}).source,
        })


      })

      return showdata
    },
    update_charts(date, type, checkVal) {
      if (date) {
        this.changeDate1(date, type, checkVal)
      }
      else {
        return //date为空不处理理
      }
    },
    changeDate1(date, type, checkVal) {
      // console.log(this.checkOptions)

      getHistoryData({
        dates: date,
        checkval: checkVal,
        type: type,
        base_id: this.selected_base
      }).then(res => {
        if (type == 'TEM') {
          this.chart_dates1 = res.data.TEM
          this.loading1 = false
          // this.renderLine('chart1', this.chart_dates);
          this.showdata1 = this.getshowdata(this.chart_dates1, this.checkVal1)
        } else if (type == 'PH') {
          this.chart_dates2 = res.data.PH
          this.showdata2 = this.getshowdata(this.chart_dates2, this.checkVal2)
          this.loading2 = false
          // this.renderLine('chart2', this.chart_dates2);
        } else if (type == 'O2') {
          this.chart_dates3 = res.data.O2
          this.showdata3 = this.getshowdata(this.chart_dates3, this.checkVal3)
          this.loading3 = false
          // this.renderLine('chart3', this.chart_dates3)
        }
        else if (type == 'CONDUCTANCE') {
          this.chart_dates4 = res.data.con
          this.showdata4 = this.getshowdata(this.chart_dates4, this.checkVal4)
          this.loading4 = false
          // this.renderLine('chart3', this.chart_dates3)
        }
      })
    },

    formatDate(date) {//日期格式化函数  
      var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

      if (month.length < 2)
        month = '0' + month;
      if (day.length < 2)
        day = '0' + day;

      return [year, month, day].join('-');
    },
    getList() {
      this.selected_base = this.$route.query.base_id; // Get base_id from the query
      this.updateBaseDataByName(this.selected_base); 
      
    },
    updateBaseDataByName(base_id) {
      get_equipments({
        base_id: base_id
      }).then(res => {
        // console.log(res)
        if (res.status) {
          this.checkOptions = res.result.equipments.map(equipment => ({
        name: equipment.EQUIPMENT_NAME,
        id: equipment.ID
          }));
          this.checkVal1 = this.checkVal2 = this.checkVal3 = this.checkVal4 = this.checkVal5 = this.checkVal6 = []
          var now_date = new Date()
          this.date1 = this.date2 = this.date3 = this.date4 = this.date5 = this.date6 = [this.formatDate(now_date), this.formatDate(now_date)]
        }
        else {
          return
        }
      })



      this.pieData = [
        { value: 1048, name: '设备 A' },
        { value: 735, name: '设备 B' },
        { value: 580, name: '设备 C' },
        { value: 484, name: '设备 D' },
        { value: 300, name: '设备 E' }
      ];

    },


    limit_reached() {
      if (this.checkOptions.length > 5) {
        return true;
      }
      return false;
    },
    resize() {
      Object.values(this.chartObj).forEach((item) => {
        item.resize();
      })
    },
    renderLine(className, data) {
      var dom = document.getElementsByClassName(className)[0];
      let chart = echarts.init(dom);
      let series = [];
      var option = {};
      console.log('data:', data);
      data.forEach((item, index) => {
        series.push({
          smooth: true,
          symbol: 'circle',
          symbolSize: 2,
          color: colorList[index],
          lineStyle: {
            width: 3
          },
          datasetIndex: index,
          connectNulls: false,
          type: 'scatter',


        })

      })
      option = {

        tooltip: {
          trigger: 'axis',
          // padding: [10, 15],
          backgroundColor: 'rgba(255, 255, 255, 0.4)',
          textStyle: { color: '#000' }
        },
        grid: {
          left: '2%',
          right: 0,
          top: '5%',
          bottom: '5%',
          containLabel: true
        },
        dataset: data,
        xAxis: {
          type: 'time',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          },
          axisLabel: {
            color: '#fff'
          },
          minInterval: 60 * 20,

          maxInterval: 3600 * 24 * 1000,

          // data: data.x

        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          },
          axisLabel: {
            color: '#fff'
          }
        },
        series: series,
        dataZoom: [//加上dataZoom可实现缩放
          {
            type: 'slider',//x轴
            xAxisIndex: 0,

          },
          {
            type: 'inside',//x轴
            xAxisIndex: 0,
            zoomOnMouseWheel: 'alt',//如何触发缩放。可选值为：true：表示不按任何功能键，鼠标滚轮能触发缩放。false：表示鼠标滚轮不能触发缩放。'shift'：表示按住 shift 和鼠标滚轮能触发缩放。'ctrl'：表示按住 ctrl 和鼠标滚轮能触发缩放。'alt'：表示按住 alt 和鼠标滚轮能触发缩放。
          },
        ],
      };
      chart.clear()
      chart.setOption(option);
      this.chartObj[className] = chart;
    },
    renderBar(className, data) {
      const chart = this.$echarts.init(document.getElementsByClassName(className)[0]);
      const series = [];
      data.y.forEach((item, index) => {
        series.push({
          type: 'bar',
          barWidth: 10,
          color: colorList[index],
          ...item
        })
      })
      const option = {
        tooltip: {
          padding: [10, 15],
          backgroundColor: 'rgba(0, 0, 0, 0.4)'
        },
        grid: {
          left: '2%',
          right: 0,
          top: '5%',
          bottom: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#fff'
          },
          data: data.x
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          },
          axisLabel: {
            color: '#fff'
          }
        },
        series
      };

      chart.setOption(option);
      this.chartObj[className] = chart;
    },
    renderPie(className, name, data, type) {
      const chart = this.$echarts.init(document.getElementsByClassName(className)[0]);
      const series = [];
      data.forEach((item, index) => {
        series.push({
          itemStyle: {
            color: colorList[index],
          },
          ...item
        })
      })
      const option = {
        tooltip: {
          trigger: 'item',
          padding: [10, 15],
          backgroundColor: 'rgba(0, 0, 0, 0.4)'
        },
        series: [
          {
            name,
            type: 'pie',
            radius: type ? ['20%', '60%'] : '60%',
            itemStyle: {
              borderWidth: 4,
              borderColor: '#1d2c4e'
            },
            data: series
          }
        ]
      };
      chart.setOption(option);

      this.chartObj[className] = chart;
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/assets/style/variable.less';

/deep/ .el-input__inner {
  background: @colorCommon;
  border: none;
  color: @colorWhite;

  &::placeholder {
    color: @colorWhite;
  }

  .el-input__icon {
    &::before {
      color: @colorWhite;
    }
  }
}

/deep/ .el-checkbox-group {
  .el-checkbox {
    color: @colorWhite;
    font-weight: bold;

    &.is-checked {
      .el-checkbox__inner {
        background: @colorWarning;
        border-color: @colorWarning;
      }

      .el-checkbox__label {
        color: @colorWarning;
      }
    }
  }
}
</style>
